import {reqGetCode,reqUserLogin,reqUserRegister,reqUserInfo,reqUserLogout} from '@/api/index'
import {setToken,getToken, removeToken} from '@/utils/token'
import { remove } from 'nprogress'
// 登录与注册模块
const state = {
  code:'',
  token:getToken(),
  userInfo:{}
}
const mutations = {
  GETCODE(state,code){
    state.code = code
  },
  USERLOGIN(state,token){
    state.token = token
  },
  GETUSERINFO(state,userInfo){
    state.userInfo = userInfo
  },
  // 清除本地数据
  USERLOGOUT(state){
    // 把仓库相关用户信息清空,本地存储数据清空
    state.token = ''
    state.userInfo = ''
    removeToken()
  }
}
const actions = {
  // 获取验证码
  async getCode({commit},phone){
    // 获取验证码的接口把验证码返回到控制台了，但是正常情况是后台把验证码发到用户的手机上【省钱】
    let result = await reqGetCode(phone)
    if(result.code == 200){
      commit("GETCODE",result.data)
      return "ok"
    }else{
      return Promise.reject(new Error('faile'))
    }
  },
  //用户注册
  async userRegister({commit},user){
    let result = await reqUserRegister(user)
    if(result.code == 200){
      return "ok"
    }else{
      return Promise.reject(new Error(result.message))
    }
  }, 
  // 登录业务(token)
  async userLogin({commit},data){
    let result = await reqUserLogin(data)
    // 服务器下发的token是用户唯一的标识符(uuid)
    // 将来经常通过带token，找服务器要用户信息展示
    if(result.code == 200){
      commit('USERLOGIN',result.data.token)
      // 本地持久化存储token
      setToken(result.data.token)
      return "ok"
    }else{
      return Promise.reject(new Error(result.message))
    }
  },
  // 获取用户信息
  async getUserInfo({commit}){
    let result = await reqUserInfo()
    if(result.code == 200){
      // 提交用户信息
      commit('GETUSERINFO',result.data)
      return "ok"
    }else{
      return Promise.reject(new Error(result.message))
    }
  },
  // 退出登录
  async userLogout({commit}){
    // 只是向服务器发送请求，通知服务器清除token
    let result = await reqUserLogout()
    // action不能操作state，必须提交给mutation才能操作修改
    if(result.code == 200){
      commit('USERLOGOUT')
    }
  }
}
const getters = {}

export default{
  state,mutations,actions,getters
}
